<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pay extends MY_Controller {

	function Pay()
	{
		parent::MY_Controller();
	}

	function methods(){
		parent::unset_session_value('order');
		$method = $this->input->post('pay_method');
		$order_id = $this->input->post('order_id');
        //print_r($_POST);exit;
		switch ($method){
			case 'alipay':
				self::aliplay($order_id);break;
            case 'bank':
                self::bank();break;
			default:break;
		}
	}

	function aliplay($order_id){
        $this->load->helper('common');
		$info = get_order_info($order_id);
        //print_r($info);exit;
		$this->config->load('alipay_config');
		$security_code = $this->config->item('alipay_security_code');
		$sign_type = $this->config->item('alipay_sign_type');
		$parameter = array(
					"service"         => "create_direct_pay_by_user",  //交易类型
					"partner"         => $this->config->item('alipay_partner'),          //合作商户号
					"return_url"      => $this->config->item('alipay_return_url'),       //同步返回
					"notify_url"      => $this->config->item('alipay_notify_url'),       //异步返回
					"_input_charset"  => $this->config->item('alipay_input_charset'),   //字符集，默认为GBK
					"subject"         => $info['p_name'],        //商品名称，必填
					"body"            => $info['p_name'],        //商品描述，必填
					"out_trade_no"    => $info['order_id'],      //商品外部交易号，必填（保证唯一性）
					"total_fee"       => $info['real_price'],         //商品单价，必填（价格不能为0）
					"payment_type"    => "1",               	 //默认为1,不需要修改

					"show_url"        => $this->config->item('alipay_show_url'),         //商品相关网站
					"seller_email"    => $this->config->item('alipay_seller_email')      //卖家邮箱，必填
					);
        //print_r($parameter);exit;
		log_common('alipay','pay.php','aliplay','parameter',$parameter);
		$configs['parameter'] 		= $parameter;
		$configs['security_code'] 	= $security_code;
		$configs['sign_type'] 		= $sign_type;
		log_common('alipay','pay.php','aliplay','aliplay_service',$configs);
		$this->load->library('alipay_service',$configs);
		$link = $this->alipay_service->create_url();
        log_common('alipay','pay.php','aliplay','alipay_link',array('link'=>$link));
		echo "<script type='text/javascript'>window.location.href =\"$link\";</script>";
	}

    function bank(){
        $this->load->helper('page');
		page_common();
        $this->template->view('v1/pay_bank');
    }

	function alipay_return(){
        parse_str($this->input->server('QUERY_STRING'), $get);
        log_common('alipay','pay.php','alipay_return','return params',$get);

        $this->config->load('alipay_config');

		$configs['partner'] 		= $this->config->item('alipay_partner');
		$configs['security_code'] 	= $this->config->item('alipay_security_code');
		$configs['sign_type'] 		= $this->config->item('alipay_sign_type');
		$configs['_input_charset'] 	= $this->config->item('alipay_input_charset');
		$configs['transport'] 		= $this->config->item('alipay_transport');

		log_common('alipay','pay.php','alipay_return','verify_configs',$configs);

		$this->load->library('alipay_notify',$configs);
		$verify_result = $this->alipay_notify->return_verify($get);

		//获取支付宝的反馈参数
		$dingdan    = $get['out_trade_no'];   //获取订单号
		$total_fee  = $get['total_fee'];      //获取总价格

		log_common('alipay','pay.php','alipay_return','verify_result',array('dingdan'=>$dingdan,'total_fee'=>$total_fee));

		if($verify_result) {    //认证合格
			//echo "success";
			//这里放入你自定义代码,比如根据不同的trade_status进行不同操作
			log_common('alipay','pay.php','alipay_return','trade success');
			//如果您申请了支付宝的购物卷功能，请在返回的信息里面不要做金额的判断，否则会出现校验通不过，出现调单。如果您需要获取买家所使用购物卷的金额,
			//请获取返回信息的这个字段discount的值，取绝对值，就是买家付款优惠的金额。即 原订单的总金额=买家付款返回的金额total_fee +|discount|.
			$res = self::_update_order_state($dingdan,$total_fee) ? '1' : '0';
			$pay_res = '支付成功！';
		} else {    //认证不合格
			//echo "fail";
			log_common('alipay','pay.php','alipay_return','trade fail');
			$pay_res = '支付失败！';
			$res = '0';
		}
        //parent::unset_session_value('order');
		self::pay_result($pay_res,$res);
	}

	function pay_result($pay_res,$order_res){
		$this->load->helper('page');
		page_common();
		$this->template->view('v1/pay_result',array('pay_res'=>$pay_res,'order_res'=>$order_res));
	}

	function alipay_notify(){

		$this->config->load('alipay_config');

		$configs['partner'] 		= $this->config->item('alipay_partner');
		$configs['security_code'] 	= $this->config->item('alipay_security_code');
		$configs['sign_type'] 		= $this->config->item('alipay_sign_type');
		$configs['_input_charset'] 	= $this->config->item('alipay_input_charset');
		$configs['transport'] 		= $this->config->item('alipay_transport');
		$this->load->library('alipay_notify',$configs);
		$verify_result = $this->alipay_notify->notify_verify();

		if($verify_result) {   //认证合格
		 //获取支付宝的反馈参数
		    $dingdan  = $this->input->post('out_trade_no');    //获取支付宝传递过来的订单号
		    $total    = $this->input->post('total_fee');       //获取支付宝传递过来的总价格
			log_common('alipay','pay.php','alipay_notify','verify_success',array('dingdan'=>$dingdan,'total'=>$total));
		/*
			获取支付宝反馈过来的状态,根据不同的状态来更新数据库
			WAIT_BUYER_PAY(表示等待买家付款);
			TRADE_FINISHED(表示交易已经成功结束);
		*/
			if($this->input->post('trade_status') == 'WAIT_BUYER_PAY') {         //等待买家付款
				//这里放入你自定义代码,比如根据不同的trade_status进行不同操作
				echo "success";
				log_common('alipay','pay.php','alipay_notify','verify_success');
			} else if ($this->input->post('trade_status') == 'TRADE_FINISHED' ||$this->input->post('trade_status') == 'TRADE_SUCCESS') {    //交易成功结束
		        //这里放入你自定义代码,比如根据不同的trade_status进行不同操作
				echo "success";
				//如果您申请了支付宝的购物卷功能，请在返回的信息里面不要做金额的判断，否则会出现校验通不过，出现调单。如果您需要获取买家所使用购物卷的金额,
				//请获取返回信息的这个字段discount的值，取绝对值，就是买家付款优惠的金额。即 原订单的总金额=买家付款返回的金额total_fee +|discount|.
				log_common('alipay','pay.php','alipay_notify','verify_success');
			} else {
				echo "fail";
				log_common('alipay','pay.php','alipay_notify','verify_failed');
			}
		} else {    //认证不合格
			echo "fail";
			log_common('alipay','pay.php','alipay_notify','verify_failed');
		}
	}

	function _update_order_state($order_id,$total){
		$this->load->model('Morders');
		$info = $this->Morders->get_order_info($order_id);
		if (($info['real_price'] - $info['pay_count']) <= $total){
			$pay_state = 1;
			$order_state = 2;
		} else {
			$pay_state = 0;
			$order_state = 1;
		}
		$pay_time = date('Y-m-d H:i:s');
		$data = array('pay_count'=>$total,'order_state'=>$order_state,'pay_state'=>$pay_state,'pay_time'=>$pay_time);
		log_common('order','pay.php','_update_order_state','state_data',$data);
		if($this->Morders->update_order_data($order_id,$data)){
			log_common('order','pay.php','_update_order_state','order_data update success');
			self::_update_user_discount($info['uid'],$order_id,$total,$info['price']);
			if($pay_state == 1){
                self::_update_member_data($info['uid']);
            }
            return true;
		} else {
			log_common('order','pay.php','_update_order_state','order_data update fail');
			return false;
		}
	}

	function _update_user_discount($username,$order_id,$count,$price){
		$this->load->model('Mmember');
		$flag = $this->Mmember->check_user_exist($username);
		if ($flag){
			$user_info = $this->Mmember->get_user_info('username',$username);
			$disc_type = $user_info['disc_type'];
			/*
			if ($disc_type == 1){
				$discount = $user_info['discount'];
			} elseif ($disc_type == 2){
				$discount = $real_price * ($user_info['discount']/100);
			} else {
				$discount = 0;
			}
			*/
			$this->load->model('Mconfigs');
			$banus = $this->Mconfigs->get_banus_config($user_info['utype']);
            $this->load->helper('common');
			$discount = get_discount($username,$order_id);
			$banus = $price * ($banus/100);
			$add_time = date('Y-m-d H:i:s');
			$values = array('username'=>$username,'order_id'=>$order_id,'price'=>$price,'discount'=>$discount,'banus'=>$banus,'add_time'=>$add_time);
			log_common('discount','pay.php','_update_user_discount','values',$values);
			return $this->Mmember->insert_new_discount($values);
		} else {
			log_common('discount','pay.php','_update_user_discount','username:'.$username.' not exists');
			return;
		}
	}

    function _update_member_data($username){
        $this->load->model('Mmember');
        $flag = $this->Mmember->check_user_exist($username);
        if($flag){
            $user = $this->Mmember->get_user_info('username',$username);
            $user['order_count']++;
            if($user['order_count'] != 0 && substr($username,0,2) == 'CM'){
                if(!($user['order_count']%10)){
                    /*
                	if($user['disc_type'] == 1){
                        $user['discount']++;
                    } elseif ($user['disc_type'] == 2){
                        $user['discount'] += 0.1;
                    }
                    */
                    $user['discount'] += 0.1;
                }
                if(!($user['order_count']%100)){
                    $user['lvl']++;
                    $user['discount'] = round($user['discount']);
                }
                $max = $this->config->item('member_dis_max');
                if($user['discount'] >= $max){
                	$user['discount'] = $max;
                }
            }
            $data = array('order_count'=>$user['order_count'],'lvl'=>$user['lvl'],'discount'=>$user['discount']);
            return $this->Mmember->update_member_data($user['uid'],$data);
        } else {
            return false;
        }
    }


	function _get_order_info($order_id) {
        $this->load->model('Morders');
        $info = $this->Morders->get_order_info($order_id);
        $info['order_discount'] = self::_get_order_discount($order_id);
        $this->load->model('Mproduct');
        $p_info = $this->Mproduct->get_product_info($info['product']);
        if(!empty($p_info)){
            $info['p_name'] = $p_info['p_name'];
            $info['p_days'] = $p_info['p_days'];
            $info['week_num'] = $p_info['week_num'];
            $info['week_money'] = $p_info['week_money'];
        } else {
            $info['p_name'] = '';
            $info['p_days'] = '';
            $info['week_num'] = 0;
            $info['week_money'] = 0;
        }
        $this->config->load('setup');
        $states = $this->config->item('member_state');
        $info['state_desc'] = $states[$info['order_state']];
        $this->load->model('Mgames');
        $info['game_name']      = $this->Mgames->get_game_name($info['game_id']);
        $info['area_name']      = $this->Mgames->get_area_name($info['game_area']);
        $info['server_name']    = $this->Mgames->get_server_name($info['game_server']);
        $info['group_name']     = $this->Mgames->get_group_info('en_name',$info['role_group'],'cn_name');
        $info['career_name']    = $this->Mgames->get_career_info('en_name',$info['role_career'],'cn_name');
        return $info;
    }
}